# coding:utf-8

import sys
sys.path.append("../utils/")

from mongo import getCollection
from excel import readExcel

conn_str = "mongodb://192.168.8.60:27017"
db_name = "qst"
address_collection_name = "address"

address = getCollection(conn_str, db_name, address_collection_name)

file_path = u"../qst/../四级地址更新_20190731.xlsx"

province_res = readExcel(file_path, 'province_0726')
city_res = readExcel(file_path, 'city_0726')
area_res = readExcel(file_path, 'area_0726')
town_res = readExcel(file_path, 'towns_0726')

list = []

for pro in province_res:
    new_pro = {
        'code': str(int(pro['code'])),
        'name': pro['name'],
        'isLeaf': False,
        'children': []
    }

    for city in city_res:
        if city['provincecode'] == pro['code']:
            new_city = {
                'code': str(int(city['code'])),
                'name': city['name'],
                'isLeaf': False,
                'children': []
            }

            for area in area_res:
                if area['citycode'] == city['code']:
                    new_area = {
                        'code': str(int(area['code'])),
                        'name': area['name'],
                        'isLeaf': False,
                        'children': []
                    }

                    for town in town_res:
                        if town['areacode'] == area['code']:
                            new_town = {
                                'code': str(int(town['code'])),
                                'name': town['name'],
                                'isLeaf': True,
                                'children': []
                            }

                            new_area['children'].append(new_town)

                    if len(new_area['children']) == 0:
                        new_area['isLeaf'] = True
                    new_city['children'].append(new_area)

            if len(new_city['children']) == 0:
                new_city['isLeaf'] = True
            new_pro['children'].append(new_city)

    if len(new_pro['children']) == 0:
        new_pro['isLeaf'] = True
    list.append(new_pro)

address.insert_many(list)
